﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Cirrious.MvvmCross.Application;
using Cirrious.MvvmCross.Interfaces.ViewModels;
using TeaLightV5.Foundation.MvvmCross.Interfaces.ViewModels;
using TeaLightV5.Foundation.MvvmCross.ViewModels;

namespace TeaLightV5.Foundation.MvvmCross.Application
{
    public class TeaViewModelLocator : MvxDefaultViewModelLocator, ITeaViewModelLocator
    {
        public bool TryLoad(Type viewModelType, ITeaViewModelParameters parameters, out IMvxViewModel model)
        {
            model = null;
            var constructor = viewModelType
                .GetConstructors()
                .FirstOrDefault(c => c.GetParameters().All(p => typeof(ITeaViewModelParameters).IsAssignableFrom(p.ParameterType)));

            if (constructor == null)
                return false;

            model = Activator.CreateInstance(viewModelType, new object[] { parameters }) as IMvxViewModel;
            return (model != null);
        }
    }
}